#pragma once

#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <cerrno>
#include "ThreadPool.hpp"
#include "Task.hpp"
#include "log.hpp"
#include "daemon.hpp"
#include "err.hpp"

using func_t = std::function<std::string(const std::string &)>;

const int backlog = 32;

class ns_server
{
public:
    ns_server(uint16_t port, func_t func)
        : _port(port), _func(func)
    {
    }

    void init()
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            LogMessage(Fatal, "creat socket fail,errno : %d , error : %s", errno, strerror(errno));
            exit(SOCK_ERR);
        }
        LogMessage(Debug, "creat socket success");

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port = htons(_port);
        if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LogMessage(Fatal, "bind socket fail,errno : %d , error : %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        LogMessage(Debug, "bind socket success");

        if (listen(_listensock, backlog) < 0)
        {
            LogMessage(Fatal, "listen fail,errno : %d , error : %s", errno, strerror(errno));

            exit(LISTEN_ERR);
        }
        LogMessage(Debug, "listen success");
    }

    void start()
    {
        struct sockaddr_in local;
        while (true)
        {
            memset(&local, 0, sizeof(local));
            socklen_t len = sizeof(local);
            int sock = accept(_listensock, (struct sockaddr *)&local, &len);
            if (sock < 0)
            {
                LogMessage(Warning, "accept fail,errno : %d , error : %s", errno, strerror(errno));
            }
            std::string clientIp = inet_ntoa(local.sin_addr);
            uint16_t clientPort = ntohs(local.sin_port);
            LogMessage(Debug, "%s-%d accept success", clientIp.c_str(), clientPort);

            Task task(sock, clientIp, clientPort, std::bind(&ns_server::service, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
            ThreadPool<Task>::GetInstance()->push(task);
        }
    }

    void service(int sock, std::string clientIp, uint16_t clientPort)
    {
        char buffer[1024];
        while (true)
        {
            int n = read(sock, buffer, sizeof(buffer) - 1);
            if (n < 0)
            {
                LogMessage(Warning, "read fail");
                exit(READ_ERR);
            }
            else if (n == 0)
            {
                LogMessage(Debug, "%s-%d exit", clientIp.c_str(), clientPort);
                close(sock);
                break; // 线程，不能用exit，exit是终止进程，那么所有的线程都会退出，这里只要某个线程退出
            }
            else
            {
                buffer[n] = '\0';
                std::string result = _func(buffer);
                n = write(sock, result.c_str(), result.size());
                if (n < 0)
                {
                    LogMessage(Warning, "Write fail");
                    exit(WRITE_ERR);
                }
            }
        }
    }

    ~ns_server()
    {
    }

private:
    int _listensock;
    uint16_t _port;
    func_t _func;
};
